import {
  Form,
  FormItem,
  Input,
  RangePicker,
  Select,
  SelectOption,
  Space,
  Textarea,
  Upload
} from 'ant-design-vue'
import { defineComponent, PropType, ref, watch } from 'vue'
import { useRoute } from 'vue-router'

import { commonApi, unpackApi } from '@/apis'
import { SvgIcon } from '@/components'
import { FROM_DATA } from '@/views/marketing/unpack/types'

import styles from './index.module.css'

const { useForm } = Form

export default defineComponent({
  name: 'BaseForm',
  props: {
    formData: {
      type: Object as PropType<FROM_DATA>,
      required: true
    }
  },
  emits: ['handleBaseUpload'],
  setup(props, { emit }) {
    const fileList = ref({
      activityMobileBackground: [] as FileItem[],
      activityIndexBanner: [] as FileItem[]
    })
    const route = useRoute()
    watch(
      () => props.formData.activityMobileBackground,
      () => {
        console.log(props.formData.activityMobileBackground)
        if (props.formData.activityMobileBackground) {
          fileList.value.activityMobileBackground = [
            {
              uid: Math.random().toString().slice(-5),
              url: props.formData.activityMobileBackground
            }
          ] as FileItem[]
        }
      },
      {
        immediate: true
      }
    )
    watch(
      () => props.formData.activityIndexBanner,
      () => {
        if (props.formData.activityIndexBanner) {
          fileList.value.activityIndexBanner = [
            {
              uid: props.formData.activityIndexBanner
                ? Math.random().toString().slice(-5)
                : '',
              url: props.formData.activityIndexBanner
            }
          ] as FileItem[]
        }
      },
      {
        immediate: true
      }
    )
    const rulesRef = ref({
      activityName: [
        {
          required: true,
          message: '请输入活动名称'
        }
      ],
      date: [
        {
          required: true,
          message: '请选择活动周期'
        }
      ],
      activityTemplate: [
        {
          required: true,
          message: '请选择活动模板'
        }
      ],
      activityInfo: [
        {
          required: true,
          message: '请输入活动详情'
        }
      ],
      activityMobileBackground: [
        {
          required: true,
          message: '请上传全面屏手机活动背景'
        }
      ],
      activityIndexBanner: [
        {
          required: true,
          message: '请上传活动首页宣传图'
        }
      ]
    } as FormRules)
    const templateOption = ref([] as any)
    const { validate, validateInfos } = useForm(props.formData, rulesRef.value)
    function submit() {
      return new Promise<void>((resolve, reject) => {
        validate().then(() => {
          const data = {
            startTime: props.formData.date[0].format('x'),
            endTime: props.formData.date[1].format('x'),
            id: route.query.id ? (route.query.id as string) : ''
          }
          unpackApi.checkActivityTime(data).then(res => {
            if (res.result) {
              resolve()
            } else {
              reject('当前时间不可用')
            }
          })
        })
      })
    }
    function handleUploadChange(key, file: FileInfo) {
      fileList.value[key] = file.fileList
      if (file.file.status === 'done') {
        emit('handleBaseUpload', {
          name: key,
          url: file.fileList[0].response.data
        })
      }
    }
    function handleRemoveUpload(key, file: FileInfo) {
      emit('handleBaseUpload', {
        name: key,
        url: ''
      })
    }
    return {
      validateInfos,
      templateOption,
      fileList,
      submit,
      validate,
      handleUploadChange,
      handleRemoveUpload
    }
  },
  render() {
    return (
      <div class={styles.wrap}>
        <Form wrapperCol={{ span: 5 }}>
          <FormItem label="活动名称" {...this.validateInfos['activityName']}>
            <Input v-model:value={this.formData.activityName} />
          </FormItem>
          <FormItem label="活动周期" {...this.validateInfos['date']}>
            <RangePicker
              v-model:value={this.formData.date}
              format="YYYY-MM-DD HH:mm"
              showTime={{ format: 'HH:mm' }}
            />
          </FormItem>
          <FormItem
            label="活动模板"
            {...this.validateInfos['activityTemplate']}
          >
            <Select v-model:value={this.formData.activityTemplate}>
              <SelectOption value={1}>九宫格</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="活动详情" {...this.validateInfos['activityInfo']}>
            <Textarea
              v-model:value={this.formData.activityInfo}
              placeholder="请输入活动详情"
              autoSize
            />
          </FormItem>
          <FormItem
            label="全面屏手机活动背景"
            {...this.validateInfos['activityMobileBackground']}
          >
            <Upload
              listType="picture-card"
              fileList={this.fileList.activityMobileBackground}
              action={commonApi.uploadFileUrl}
              onChange={(info: FileInfo) =>
                this.handleUploadChange('activityMobileBackground', info)
              }
              remove={args =>
                this.handleRemoveUpload('activityMobileBackground', args)
              }
              showUploadList={{
                showPreviewIcon: false,
                showRemoveIcon: true
              }}
            >
              {!this.formData.activityMobileBackground ? (
                <div>
                  <SvgIcon name="upload" />
                  <div>从图库中选择</div>
                </div>
              ) : null}
            </Upload>
            <span class={styles.tips}>建议尺寸：750*960</span>
          </FormItem>
          <FormItem
            label="活动首页宣传图"
            {...this.validateInfos['activityIndexBanner']}
          >
            <Upload
              listType="picture-card"
              fileList={this.fileList.activityIndexBanner}
              action={commonApi.uploadFileUrl}
              onChange={(info: FileInfo) =>
                this.handleUploadChange('activityIndexBanner', info)
              }
              remove={args =>
                this.handleRemoveUpload('activityIndexBanner', args)
              }
              showUploadList={{
                showPreviewIcon: false,
                showRemoveIcon: true
              }}
            >
              {!this.formData.activityIndexBanner ? (
                <div>
                  <SvgIcon name="upload" />
                  <div>从图库中选择</div>
                </div>
              ) : null}
            </Upload>
            <span class={styles.tips}>建议尺寸：750*304</span>
          </FormItem>
          <FormItem label="按钮文字配置" style={{ display: 'none' }}>
            <Space>
              <span>按钮背景: </span>
              <Input
                type="color"
                v-model:value={this.formData.buttonBackground}
                style={{ width: '50px' }}
              />
              <span>按钮文字: </span>
              <Input
                type="color"
                v-model:value={this.formData.buttonWord}
                style={{ width: '50px' }}
              />
            </Space>
          </FormItem>
        </Form>
      </div>
    )
  }
})
